package com.vehiclesecure.controller;

import com.vehiclesecure.service.VehicleUserSyncService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * 车辆用户同步控制器
 * 提供手动触发车辆用户同步的API接口
 */
@RestController
@RequestMapping("/api/sync")
public class VehicleUserSyncController {

    private final VehicleUserSyncService vehicleUserSyncService;

    @Autowired
    public VehicleUserSyncController(VehicleUserSyncService vehicleUserSyncService) {
        this.vehicleUserSyncService = vehicleUserSyncService;
    }

    /**
     * 手动触发所有车辆的用户同步
     * 仅管理员可以调用
     * @return 同步结果
     */
    @PostMapping("/vehicle-users")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<?> syncVehicleUsers() {
        try {
            vehicleUserSyncService.syncAllVehicleUsers();
            vehicleUserSyncService.fixOrphanedVehicles();
            
            return ResponseEntity.ok(Map.of(
                "success", true,
                "message", "车辆用户同步完成"
            ));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(Map.of(
                "success", false,
                "error", e.getMessage()
            ));
        }
    }

    /**
     * 修复孤立车辆（没有ownerId的车辆）
     * 仅管理员可以调用
     * @return 修复结果
     */
    @PostMapping("/fix-orphaned-vehicles")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<?> fixOrphanedVehicles() {
        try {
            vehicleUserSyncService.fixOrphanedVehicles();
            
            return ResponseEntity.ok(Map.of(
                "success", true,
                "message", "孤立车辆修复完成"
            ));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(Map.of(
                "success", false,
                "error", e.getMessage()
            ));
        }
    }
}